package com.xxx.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Result;
import com.xxx.dto.WarningDto;
import com.xxx.enums.Properties;
import com.xxx.pojo.Metrics;
import com.xxx.pojo.RangeWarning;
import com.xxx.service.MetricsService;
import com.xxx.service.RangeWarningService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/warning")
public class RangeWarningController {

    @Autowired
    private RangeWarningService warningService;

    @Autowired
    private MetricsService metricsService;

    /**
     * 增加预警范围
     * @param warningDto
     * @return
     */
    @Transactional
    @PostMapping("/save")
    @PreAuthorize("hasAnyAuthority('sys:add:warning')")
    public Result save(@RequestBody WarningDto warningDto){
        log.info("warningDto:{}",warningDto);
        warningDto.setUpdateTime(LocalDateTime.now());

        RangeWarning rangeWarning = new RangeWarning();
        BeanUtils.copyProperties(warningDto,rangeWarning);


        boolean save = warningService.save(rangeWarning);
        List<Metrics> metricsList = warningDto.getMetricsList();

        metricsList.stream().forEach(metrics -> {
            metrics.setWarningId(rangeWarning.getId());
            if(!metricsService.save(metrics)){
                throw new RuntimeException("metrics存储出错");
            }
        });

        return save ? Result.success("保存成功") : Result.error("保存失败");
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @Transactional
    @DeleteMapping("/del/{id}")
    @PreAuthorize("hasAnyAuthority('sys:deleted:warning')")
    public Result delById(@PathVariable Integer id){

        boolean b = warningService.removeById(id);

        boolean remove = metricsService.delByWarningId(id);

        return b == remove && remove == true ? Result.success("删除成功") : Result.error("删除失败");
    }


    /**
     * 更新预警范围
     * @param warningDto
     * @return
     */
    @Transactional
    @PutMapping("/update")
    @PreAuthorize("hasAnyAuthority('sys:update:warning')")
    public Result update(@RequestBody WarningDto warningDto){

        log.info("warningDto:{}",warningDto);
        boolean b = warningService.updateById(warningDto);
        metricsService.delByWarningId(warningDto.getId());

        warningDto.getMetricsList().stream().forEach(metrics -> {
            metrics.setWarningId(warningDto.getId());
            if(!metricsService.save(metrics)){
                throw new RuntimeException("metrics存储出错");
            }
        });

        return b ? Result.success("修改成功") : Result.error("修改失败");
    }

    @PostMapping("/get-warning")
    @PreAuthorize("hasAnyAuthority('sys:select:warning')")
    public Result getByPage(Integer pageSize, Integer pageNo,@RequestBody RangeWarning rangeWarning){
        log.info("rangeWarning:{}",rangeWarning);

        IPage iPage = new Page(pageNo, pageSize);
        iPage = warningService.page(iPage, new LambdaQueryWrapper<RangeWarning>()
                .eq(rangeWarning.getMetrics() != null, RangeWarning::getMetrics, rangeWarning.getMetrics().getI())
                .eq(rangeWarning.getWarningContent() != null, RangeWarning::getWarningContent, rangeWarning.getWarningContent().getI())
                .like(rangeWarning.getClassification() != null, RangeWarning::getClassification, rangeWarning.getClassification())
                );

        return Result.success("查询成功",iPage);
    }
}
